package com.rr.mymoney.jsf.util;

import java.io.Serializable;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang.StringUtils;

import com.rr.mymoney.jsf.CategoriesController;
import com.rr.mymoney.model.Category;

@FacesConverter(value = "categoryConverter", forClass = Category.class)
public class CategoryConverter implements Converter, Serializable {

    private static final long serialVersionUID = -2452218002468844630L;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
	if (StringUtils.isEmpty(value)) {
	    return null;
	}
	CategoriesController controller = context.getApplication().evaluateExpressionGet(context, "#{categoriesController}",
		CategoriesController.class);
	Category category = controller.getCategory(value);
	return category;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
	if (value instanceof Category) {
	    return ((Category) value).getId() + "";
	}
	if (value != null) {
	    return value.toString();
	}
	return null;
    }
}
